package com.shyroke.service.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shyroke.entity.Role;
import com.shyroke.entity.User;
import com.shyroke.entity.UserInfo;
import com.shyroke.entity.UserRoleKey;
import com.shyroke.mapper.UserInfoMapper;
import com.shyroke.mapper.UserMapper;
import com.shyroke.mapper.UserRoleMapper;
import com.shyroke.service.UserServiceI;

@Service
public class UserServiceImpl implements UserServiceI {

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private UserRoleMapper userRoleMapper;

	@Override
	public User selectUserByUserNameAndPwd(String username, String password) {
		return userMapper.selectUserByUserNameAndPwd(username, password);
	}

	@Override
	public List<Role> selectRolesByUserId(int userId) {
		return userMapper.selectRolesByUserId(userId);
	}

	@Override
	public User selectByUserId(int userId) {
		return userMapper.selectByPrimaryKey(userId);
	}

	@Override
	public boolean isExitEmail(String email) {

		String userId = userInfoMapper.isExitEmail(email);

		if (userId != null) {
			// 说明存在该email
			return true;
		} else {
			return false;
		}

	}

	@Override
	public void insert(User user) {
		user.setName("普通用户");
		user.setState("0");
		userMapper.insert(user);
		User user1 = userMapper.selectUserByUserNameAndPwd(user.getUsername(), user.getPassword());

		/*
		 * 设置新注册用户的角色
		 */
		UserRoleKey userRole = new UserRoleKey();
		userRole.setRoleId(2);
		userRole.setUserId(user1.getId());
		userRoleMapper.insert(userRole);

	}

	@Override
	public void update(User user) {
		userMapper.updateByPrimaryKeySelective(user);
	}

	@Override
	public boolean isPwdCorret(Integer id, String repassword) {

		User user = userMapper.isPwdCorret(id, repassword);

		if (user != null) {
			return true;
		} else {
			return false;
		}

	}

	@Override
	public List<User> selectAll(int beginIndex, int endIndex) {
		return userMapper.selectAll(beginIndex, endIndex);
	}

	@Override
	public int selectCountByUser() {
		return userMapper.selectCountByUser();
	}

	@Override
	public List<User> selectByUserName(String username, int beginIndex, int endIndex) {
		return userMapper.selectByUserName(username, beginIndex, endIndex);
	}

	@Override
	public boolean isExitUserName(String username) {

		User user = userMapper.isExitUserName(username);

		if (user == null) {
			return false; //不存在该用户名的用户
		} else {
			return true;
		}

	}

	@Override
	public void deleteByUserId(Integer userId) {
		userMapper.deleteByPrimaryKey(userId);
	}


	@Override
	public List<User> selectByUserNameNoPage(String key) {
		return userMapper.selectByUserNameNoPage(key);
	}

}
